package com.hq.door.util;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
	private static ObjectMapper mapper;
	static {
		mapper = new ObjectMapper();
	}

	// 对象转化成为JSON
	public static String object2Json(Object objcet) {
		String json = null;
		try {
			json = mapper.writeValueAsString(objcet);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	public static String object2JsonIgnoreNull(Object objcet){
		String json = null;
		mapper.setSerializationInclusion(Include.NON_NULL);
		try {
			json = mapper.writeValueAsString(objcet);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	public static JavaType getType(Class collections, Class element) {
		return mapper.getTypeFactory().constructParametricType(collections,
				element);
	}

	// JSON转化成为对象list
	public static List json2List(String json, JavaType javaType) {
		List list = null;
		try {
			list = mapper.readValue(json, javaType);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	// JSON转化成为单一对象
	public static Object json2object(String json, Class clazz) {
		Object object = null;
		try {
			object = mapper.readValue(json, clazz);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object;

	}

}
